
from engine.strategy import *
import os, json
from logic.global_objs import g
from datetime import datetime
from enum import Enum
from .logic_utils import class_2_dict
'''
任务管理类
'''


from .logic_utils import *

class Task(object):

    name = '策略-'
    date_start = '20100101'
    date_end = datetime.now().strftime('%Y%m%d')
    enum_freq = 1

    #投资标的池
    list_codes = ['000300.SH', '000905.SH', '399006.SZ']


    enum_task_type = 1


    list_features = ['Return($close,20)']

    #交易规则
    list_buy_rules = ['Return($close,20)>0.08']
    buy_rules_min_count = 1
    list_sell_rules = ['Return($close,20)<0']
    sell_rules_min_count = 1

    #排序规则
    orderby = 'Return($close,20)'
    enum_orderby_dir = 1

    #选股
    enum_weight = 1
    weight_fix = ['0.8', '0.2']


class TaskMgr:
    def __init__(self):
        self.task_path = Config.get_config_path() + '/tasks'
        self._tasks = None

    #dict类型
    def add_or_update_task(self, task:Task):
        name = task.name
        file_name = '{}/{}.json'.format(self.task_path, name)
        with open(file_name, "w") as f:

            json.dump(class_2_dict(task),f)
        g.notify(g.TASK_CHANGED,{})

    def del_task(self, name):
        file_name = '{}/{}.json'.format(self.task_path, name)
        os.remove(file_name)
        g.notify(g.TASK_CHANGED, {})

    def get_tasks(self):
        if self._tasks:
            return self._tasks

        files = os.listdir(self.task_path)

        tasks = {}
        for file_name in files:
            with open('{}/{}'.format(self.task_path, file_name), 'r') as f:
                json_dict = json.load(f)
                task = Task()
                for k in task.__class__.__dict__.keys():
                    if '__' not in k:
                        if k in json_dict.keys():
                            task.__setattr__(k,json_dict[k])
                tasks[task.name] = task
        self._tasks = tasks
        return self._tasks

    def task_tree(self):
        task_tree = {'资产配置':[], '规则策略':[], '机器模型':[]}
        tasks = self.get_tasks()
        for name,t in tasks.items():
            type = t.enum_task_type
            if type == 1:
                task_tree['资产配置'].append(t)
            if type == 2:
                task_tree['规则策略'].append(t)
            if type == 3:
                task_tree['机器模型'].append(t)

        return task_tree

    def get_results_list(self):
        results_path = Config.get_config_path() + '/results'
        files = os.listdir(results_path)
        files = [f.replace('.csv','') for f in files]
        return files




class Config:
    tasks = None
    @staticmethod
    def get_config_path():
        file_dir = os.path.dirname(__file__)
        return os.path.dirname(file_dir) + '/config'


    @staticmethod
    def get_strategy(name):
        if name == 'buy&hold':
            return StrategyBuyHold

        if name == 'rolling':
            return StrategyRolling

        if name == 'machinelearning':
            return StrategyMachineLearning
        return None

